package org.dreamwork.sso.saml2.protocol;

import org.dreamwork.sso.saml2.util.SamlHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dreamwork.misc.XMLUtil;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.XMLObjectBuilderFactory;
import org.w3c.dom.Element;

import java.io.ByteArrayOutputStream;

/**
 * Created with IntelliJ IDEA.
 * User: seth.yang
 * Date: 13-8-17
 * Time: 上午2:03
 */
public abstract class SamlObject<T extends XMLObject> {
    protected XMLObjectBuilderFactory factory;

    protected Log logger = LogFactory.getLog (getClass ());

    protected SamlObject (XMLObjectBuilderFactory factory) {
        this.factory = factory;
    }

    protected T create (Class<T> type) {
        return SamlHelper.createObject (type, factory);
    }

    public String toXMLString () {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream ();
            XMLUtil.print (getDom (), out);
            return out.toString ("utf-8");
        } catch (Exception ex) {
            logger.warn (ex.getMessage (), ex);
            throw new RuntimeException (ex);
        }
    }

    public byte[] getXMLBytes () {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream ();
            XMLUtil.print (getDom (), out);
            return out.toByteArray ();
        } catch (Exception ex) {
            logger.warn (ex.getMessage (), ex);
            throw new RuntimeException (ex);
        }
    }

    public abstract Element getDom ();
}